import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { orderApi } from '../services/api';

export function useOrderForm() {
  // 表单数据
  const formData = reactive({
    customer_name: '',
    customer_phone: '',
    order_time: new Date().toISOString(),
    items: []
  });

  // 表单加载状态
  const loading = ref(false);

  // 商品项表单
  const itemForm = reactive({
    name: '',
    quantity: 1,
    price: 0
  });

  // 添加商品项
  const addItem = () => {
    if (!itemForm.name.trim()) {
      ElMessage.warning('请输入商品名称');
      return;
    }
    
    if (itemForm.quantity <= 0 || itemForm.price < 0) {
      ElMessage.warning('请输入有效的数量和价格');
      return;
    }

    formData.items.push({
      name: itemForm.name,
      quantity: itemForm.quantity,
      price: itemForm.price,
      subtotal: itemForm.quantity * itemForm.price
    });

    // 重置商品项表单
    itemForm.name = '';
    itemForm.quantity = 1;
    itemForm.price = 0;
  };

  // 移除商品项
  const removeItem = (index) => {
    formData.items.splice(index, 1);
  };

  // 更新商品项数量
  const updateItemQuantity = (index, value) => {
    if (value > 0) {
      formData.items[index].quantity = value;
      formData.items[index].subtotal = value * formData.items[index].price;
    }
  };

  // 更新商品项价格
  const updateItemPrice = (index, value) => {
    if (value >= 0) {
      formData.items[index].price = value;
      formData.items[index].subtotal = formData.items[index].quantity * value;
    }
  };

  // 计算订单总价
  const calculateTotal = () => {
    return formData.items.reduce((total, item) => total + item.subtotal, 0);
  };

  // 表单验证
  const validateForm = () => {
    if (!formData.customer_name.trim()) {
      ElMessage.warning('请输入客户姓名');
      return false;
    }

    if (!formData.customer_phone.trim()) {
      ElMessage.warning('请输入客户电话');
      return false;
    }

    if (formData.items.length === 0) {
      ElMessage.warning('请至少添加一个商品');
      return false;
    }

    return true;
  };

  // 提交表单
  const submitForm = async () => {
    if (!validateForm()) {
      return false;
    }

    loading.value = true;
    try {
      // 准备提交数据
      const total_amount = calculateTotal();
      const submitData = {
        customer_name: formData.customer_name,
        customer_phone: formData.customer_phone,
        total_amount: total_amount,
        items: formData.items
      };

      const response = await orderApi.createOrder(submitData);
      console.log('创建订单响应:', response);
      
      if (response && response.id) {
        // 重置表单
        resetForm();
        return true;
      } else {
        ElMessage.error('订单创建失败');
        return false;
      }
    } catch (error) {
      console.error('创建订单失败:', error);
      ElMessage.error('订单创建失败');
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    formData.customer_name = '';
    formData.customer_phone = '';
    formData.order_time = new Date().toISOString();
    formData.items = [];
    
    itemForm.name = '';
    itemForm.quantity = 1;
    itemForm.price = 0;
  };

  return {
    formData,
    loading,
    itemForm,
    addItem,
    removeItem,
    updateItemQuantity,
    updateItemPrice,
    calculateTotal,
    submitForm,
    resetForm
  };
}